// pages/cart/cart.js
import computedBehavior from 'miniprogram-computed'
Page({
  behaviors: [computedBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    isLogin: !!wx.getStorageSync('token'),
    cartList: [],
    isEditAll: false,
    // sku选择
    skuIndex: 0,
    show: false,
    productSkuData: null,
    defaultNum: 1,
    defaultSkuVid: ''
  },

  computed: {
    // 全选按钮状态
    allChecked(data) {
      return data.cartList && data.cartList.length && data.cartList.every(i => i.checked)
    },
    // 选中商品的数量,如果数量为0,则禁用提交按钮
    totalNum(data) {
      return data.cartList.reduce((prev, cur) => {
        return Number(prev) + Number(cur.checked ? cur.num : 0)
      }, 0)
    },
    // 合计价格
    totalPrice(data) {
      return data.cartList.reduce((prev, cur) => {
        return Number(prev) + Number(cur.checked ? cur.productSku.price * cur.num : 0)
      }, 0) * 100
    }
  },

  // 绑定手机号按钮点击事件(登录)
  bindgetphonenumber(e) {
    console.log(e)
    wx.login({}).then(res => {
      console.log(res)
      wx.$http.post('auth/wxLogin', {
        encryptedData: e.detail.encryptedData,
        iv: e.detail.iv,
        code: res.code
      }).then(res => {
        console.log(res)
        wx.setStorageSync('token', res.data.token)
        wx.setStorageSync('user', res.data.user)
        this.setData({
          isLogin: true
        })
        this.getCartData()
      }).catch(err => {
        console.log(err)
        wx.showToast({
          title: '授权失败,请重试!',
        })
      })
    })
  },

  // 获取购物车数据接口
  getCartData() {
    wx.$http.get('product/getUserSku').then(res => {
      res.data.forEach(item => {
        item.checked = false
      })
      this.setData({
        cartList: res.data || []
      })
      wx.setStorageSync('cartCount', res.data.reduce((prev, cur) => {
        return prev + cur.num
      }, 0))
    })
  },

  // 右上角编辑/完成按钮
  editAll() {
    console.log()
    if (!this.data.isEditAll) {
      this.selectAllComponents('.van-swipe-cell ').forEach(item => {
        item.close && item.close()
      })
    }

    this.setData({
      isEditAll: !this.data.isEditAll
    })
  },

  // 商品复选框点击事件
  selectChange(event) {
    console.log(event)
    let index = event.currentTarget.dataset.index
    let tar = `cartList[${index}].checked`
    this.setData({
      [tar]: !this.data.cartList[index].checked
    })
  },
  // sku商品数量改变事件
  changeNum(e) {
    console.log(e)
    let index = e.currentTarget.dataset.index
    let tarObj = this.data.cartList[index]
    let tar = `cartList[${index}].num`
    this.setData({
      [tar]: e.detail
    })
    wx.setStorageSync('cartCount', this.data.cartList.reduce((prev, cur) => {
      return prev + cur.num
    }, 0))
    this.updateSku({
      id: tarObj.id,
      num: tarObj.num,
      sku_id: tarObj.productSku.id,

    })
  },
  // 点击商品规格事件:弹出sku选择框
  changeSku(event) {
    console.log(event)
    const Index = event.currentTarget.dataset.index
    this.setData({
      skuIndex: Index
    })
    wx.showLoading({})
    // 获取商品规格
    wx.$http.get('product/getProductSkuList/' + this.data.cartList[Index].product.id).then(res => {
      console.log(res)
      this.setData({
        productSkuData: res.data,
        defaultNum: this.data.cartList[Index].num,
        defaultSkuVid: this.data.cartList[Index].productSku.v_ids
      })
      wx.nextTick(() => {
        this.setData({
          show: true
        })
      })
      wx.hideLoading()
    }).catch(err => {
      console.log(err)
      wx.hideLoading()
    })
  },
  // 改变sku
  confirmSku(event) {
    console.log(event)
    this.updateSku({
      id: this.data.cartList[this.data.skuIndex].id,
      num: event.detail.num,
      sku_id: event.detail.sku_id,
    })
    this.setData({
      show: false
    })
  },
  // 提交/删除按钮点击事件
  onClickButton() {
    if (this.data.isEditAll) {
      let ids = this.data.cartList.filter(i => i.checked).map(i => i.id)
      if (ids.length) {
        wx.showModal({
          content: '确认删除所选商品吗?',
          success: (res) => {
            if (res.confirm) {
              wx.$http.post('product/deleteUserSku', ids).then(res => {
                console.log(res)
                this.getCartData()
              }).catch(err => {
                console.log(err)
              })
            }
          }
        })
      } else {
        wx.showToast({
          icon: 'none',
          title: '请选择要删除的商品',
        })
      }
    }
  },
  // 全选按钮点击事件
  selectAll() {
    this.setData({
      cartList: this.data.cartList.map(i => {
        i.checked = !this.data.allChecked
        return i
      })
    })
  },
  // 点击商品左滑删除按钮
  onCloseRightSwipe(event) {
    const {
      position,
      instance
    } = event.detail;
    switch (position) {
      case 'left':
      case 'cell':
        instance.close();
        break;
      case 'right':
        wx.showModal({
          content: '确认删除所选商品吗?',
          success: (res) => {
            if (res.confirm) {
              console.log('用户点击确定')
              const Index = event.detail.name
              console.log(this.data.cartList[Index])
              wx.$http.post('product/deleteUserSku', [
                this.data.cartList[Index].id
              ]).then(res => {
                console.log(res)
                this.data.cartList.splice(Index, 1)
                this.setData({
                  cartList: this.data.cartList
                })
              }).catch(err => {
                console.log(err)
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
        break;
    }
  },

  // 更新商品sku方法
  updateSku(sku, refresh) {
    wx.showLoading({})
    wx.$http.post('product/editUserSku', sku).then(res => {
      console.log(res)
      wx.hideLoading()
      // 被合并到别的sku
      if (res.data.id != sku.id) {
        this.data.cartList.splice(this.data.cartList.findIndex(i => i.id == sku.id), 1)
      }
      this.data.cartList.find(i => i.id == res.data.id).num = res.data.num
      this.setData({
        cartList: this.data.cartList
      })
      // refresh && this.getCartData
    })
  },

  // 去逛逛吧按钮点击事件
  goIndex() {
    wx.switchTab({
      url: '/pages/home/home',
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.isLogin) this.getCartData()

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})